/*
	4. Median of Two Sorted Arrays   QuestionEditorial Solution  My Submissions
	
	There are two sorted arrays nums1 and nums2 of size m and n respectively.

	Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

	Example 1:
	nums1 = [1, 3]
	nums2 = [2]

	The median is 2.0
	Example 2:
	nums1 = [1, 2]
	nums2 = [3, 4]

	The median is (2 + 3)/2 = 2.5
*/
#include <stdio.h>
#include <stdlib.h>

double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
	if(nums1Size < 1 && nums2Size < 1)
		return 0;	

	int i = 0, j = 0;
	int iLen = 0;
	double ret;
	int iLen_Mid = (nums1Size + nums2Size)/2;
	int iTemp_Mid[2];
	char bOddOrEven;

	if((nums1Size+nums2Size)%2)
		bOddOrEven = 1;
	else
		bOddOrEven = 0;

	while(i < nums1Size || j < nums2Size)
	{
		if(j >= nums2Size || nums1[i] <= nums2[j] && i < nums1Size)
		{
			iTemp_Mid[0] = nums1[i];
			i++;
		}
		else
		{
			iTemp_Mid[0] = nums2[j];
			j++;
		}
		iLen++;
		
		if(bOddOrEven)
		{
			if(iLen == iLen_Mid + 1)
			{	
				ret = iTemp_Mid[0];
				break;
			}
		}
		else 
		{
			if(iLen == iLen_Mid)
				iTemp_Mid[1] = iTemp_Mid[0];
			else if(iLen == iLen_Mid + 1)
			{
				ret = (iTemp_Mid[0] + iTemp_Mid[1])/2.0;
				break;
			}
		}
	}

	return ret;
	
}

int main(void)
{
	int nums1[] = {};
	int nums2[] = {2};

	int nums1Size = sizeof(nums1)/sizeof(int);
	int nums2Size = sizeof(nums2)/sizeof(int);
	
	printf("ret = %lf\n", findMedianSortedArrays(nums1,nums1Size,nums2,nums2Size));
	return 0;
}

